<?php

$set_belong     = array('a', 'c');
$set_field_type = array('string', 'logic', 'select', 'multiselect', 'image', 'date', 'article', 'category', 'float', 'integer');
$set_emode      = array('Textarea','Plane','Basic','Simple','Advanced');

if(session::user() && session::user()->id == 1)
{
   $nodeId   = $FILTER->isValidInteger($request[$rlength]) ? $request[$rlength] : 0;
   $category = $nodeId ? $KERNEL->getNode($nodeId) : FALSE;

   if($commit)
   {
      $f['belong']         = !empty($_POST['f']['belong']) && in_array($_POST['f']['belong'], $set_belong) ? $_POST['f']['belong'] : 'a';
      $f['fset']           = !empty($_POST['f']['fset'])            ? TRUE                                                         : FALSE;
      $f['fset_name']      = !empty($_POST['f']['fset_name'])       ? $FILTER->getFirstAlpha($_POST['f']['fset_name'])             : FALSE;
      $f['fset_title']     = !empty($_POST['f']['fset_title'])      ? $FILTER->ClearString($_POST['f']['title'])                   : '';
      $f['name']           = !empty($_POST['f']['name'])            ? $FILTER->getFirstAlpha($_POST['f']['name'])                  : FALSE;
      $f['title']          = !empty($_POST['f']['title'])           ? $FILTER->ClearString($_POST['f']['title'])                   : FALSE;
      $f['field_type']     = !empty($_POST['f']['field_type']) && in_array($_POST['f']['field_type'], $set_field_type) ? $_POST['f']['field_type'] : FALSE;
      $f['text_default']   = !empty($_POST['f']['text_default'])    ? $FILTER->ClearString($_POST['f']['text_default'])            : '';
      $f['logic_default']  = !empty($_POST['f']['logic_default'])   ? 1                                                            : 0;
      $f['multiline']      = !empty($_POST['f']['multiline'])       ? TRUE                                                         : FALSE;
      $f['height']         = !empty($_POST['f']['height'])          ? $FILTER->getFirstInteger($_POST['f']['height'])              : 100;
      $f['emode']          = !empty($_POST['f']['emode']) && in_array($_POST['f']['emode'], $set_emode) ? $_POST['f']['emode']     : reset($set_emode);
      $f['values']         = !empty($_POST['f']['values'])          ? $_POST['f']['values']                                        : FALSE;
      $f['select_default'] = !empty($_POST['f']['select_default'])  ? $FILTER->getFirstInteger($_POST['f']['select_default'])      : '';
      $f['min_width']      = !empty($_POST['f']['min_width'])       ? $FILTER->getFirstInteger($_POST['f']['min_width'])           : 50;
      $f['min_height']     = !empty($_POST['f']['min_height'])      ? $FILTER->getFirstInteger($_POST['f']['min_height'])          : 50;
      $f['max_width']      = !empty($_POST['f']['max_width'])       ? $FILTER->getFirstInteger($_POST['f']['max_width'])           : 100;
      $f['max_height']     = !empty($_POST['f']['max_height'])      ? $FILTER->getFirstInteger($_POST['f']['max_height'])          : 100;
      $f['fix']            = !empty($_POST['f']['fix'])             ? TRUE                                                         : FALSE;


      if(!$f['belong'] || !$f['name'] || !$f['title'] || !$f['field_type'] || gettext::translate('fields', $f['name'])) $ErrorHandler->setError();
      if($f['fset'] && !$f['fset_name']) $ErrorHandler->setError();

      $params = array();
      if($ErrorHandler->getErrorStatus() == FALSE)
      {
         if($f['fset_name'])
         {
            $params['fieldset'] = $f['fset_name'];
            $params['db'] = $f['name'];
         }
         $params['type'] = $f['field_type'];

         switch($f['field_type'])
         {
            case 'article':
               break;

            case 'category':
               break;

            case 'date':
               $params['value'] = strtotime($f['text_default']) ? $f['text_default'] : 'now';
               break;

            case 'float':
               $params['value'] = (string)$FILTER->getFirstNumeric($f['text_default']);
               break;

            case 'image':
               $params['min_w'] = $f['min_width'];
               $params['min_h'] = $f['min_height'];
               $params['max_w'] = $f['max_width'];
               $params['max_h'] = $f['max_height'];
               $params['fixed'] = $f['fix'];
               break;

            case 'integer':
               $params['value'] = (string)$FILTER->getFirstInteger($f['text_default']);
               break;

            case 'logic':
               $params['value'] = $f['logic_default'];
               break;

            case 'select':
            case 'multiselect':
               $params['value'] = $f['select_default'];
               break;

            case 'string':
               $params['value']  = $f['text_default'];
               $params['html']   = $f['multiline'];
               $params['height'] = $f['height'];
               $params['emode']  = $f['emode'];
               break;
         }

         // CLEAR LANG PHRASES CACHE
         $KERNEL->clearSystemCache(false, 'phrases');
         $DB->DB_StartTransaction();

         // WRITE LANG PHRASES FOR FIELD TITLE
         $lang_var_id = $DB->DB_GetNextID('id', 'meccano_var');
         $DB->sql = 'INSERT INTO meccano_var (`id`, `lang`, `name`, `key`, `value`, `sys`)
                     VALUES ('. $lang_var_id .', '. $KERNEL->getDefaultLangId() .', "fields",
                     "'. $f['name'] .'",
                     "'. $f['title'] .'",
                     "1"
                     )';
         $DB->DB_Query();
         $new_lang_prase['fields'][$f['name']] = $f['title'];
         $KERNEL->updateLangPhraseOnFly($new_lang_prase);


         // WRITE LANG PRASES FOR SELECT OR MULTISELECT FIELD
         if(($f['field_type'] == 'select' || $f['field_type'] == 'multiselect') && is_array($f['values']))
         {
            ksort($f['values']);
            $i = 1;
            $lang_var_id = $DB->DB_GetNextID('id', 'meccano_var');
            if(gettext::translate($f['name']))
            {
               $lang_prase_name = $f['name'] .'_'. rand_string(3, array('set'=>'lower'));
            }
            else
            {
               $lang_phrase_name = $f['name'];
            }
            $params['values'] = $lang_phrase_name;
            $sql = array();
            foreach($f['values'] AS $tmp)
            {
               if(is_array($tmp))
               {
                  foreach($langs AS $l)
                  {
                     if(isset($tmp[$l['id']]))
                        $sql[] .= '('. $lang_var_id .', '. $l['id'] .', "'. $lang_phrase_name .'", '. $i .', "'. $FILTER->ClearString($tmp[$l['id']]) .'")';
                  }
                  $lang_var_id++;
                  $i++;
               }
            }

            if(!empty($sql))
            {
               $sql = 'INSERT INTO meccano_vars (`id`, `lang`, `name`, `key`, `value`) VALUES '. implode(',', $sql);
               $DB->sql = $sql;
               $DB->DB_Query();
            }
         }



         if($f['fset'] && !empty($f['fset_name']) && !empty($f['fset_title']))
         {
            $DB->sql = 'SHOW TABLES LIKE "meccano_'. $f['fset_name'] .'"';
            $DB->DB_Query();
            $fset_table_exist = $DB->DB_GetRows();

            // WRITE LANG PRASE FOR FIELDSET TITLE
            if($fset_table_exist == 0)
            {
               $lang_var_id = $DB->DB_GetNextID('id', 'meccano_var');
               $DB->sql = 'INSERT INTO meccano_vars (`id`, `lang`, `name`, `key`, `value`) VALUES (
                   '. $lang_var_id .',
                   '. $KERNEL->getDefaultLangId() .',
                   "fieldsets",
                   "'. $f['fset_name'] .'",
                   "'. $f['fset_title'] .'",
                   "1"
               )';
               $DB->DB_Query();
               $DB->sql = 'CREATE TABLE `meccano_'. $f['fset_name'] .'` (`id` int(10) unsigned NOT NULL default "0", `lang` int(2) unsigned NOT NULL default "0", `node` int(5) default NULL, `belong` enum("a","c") default "a" PRIMARY KEY  (`id`,`lang`)) ENGINE=InnoDB DEFAULT CHARSET=utf8';
               $DB->DB_Query();
            } else
            {
               $ErrorHandler->setError();
            }
         }

         // ALTER ARTICLE OR CATEGORY TABLE
         $sql  = 'ALTER TABLE `meccano_';
         if($f['fset'] && $f['fset_name'])
         {
            $sql .= $f['fset_name'];
         } elseif($f['belong'] == 'a')
         {
            $sql .= 'articles';
         } elseif($f['belong'] == 'c')
         {
             $sql .= 'treecontent';
         }
         $sql .= '` ADD `'. $f['name'] .'` ';
         switch($params['type'])
         {
            case 'string':
               $sql .= 'TEXT default NULL';
               break;
            case 'logic':
               $sql .= 'ENUM("0","1") default "'. $params['value'] .'"';
               break;
            case 'select':
            case 'multiselect':
               $sql .= 'VARCHAR(100) default NULL';
               break;
            case 'image':
               $sql .= 'TINYTEXT default NULL';
               break;
            case 'date':
               $sql .= 'DATE default NULL';
               break;
            case 'article':
            case 'category':
            case 'integer':
               $sql .= 'INT(10) default NULL';
               break;
            case 'float':
               $sql .= 'DECIMAL(12,3) default NULL';
               break;
         }
         $DB->sql = $sql;
         $DB->DB_Query();


         // ADD FIELD TO FIELDS LIST
         $field_id = $DB->DB_GetNextID('id', 'meccano_fields');
         $DB->sql = 'INSERT INTO meccano_fields (`id`, `node`, `tab`, `position`, `alias`, `lang_phrase`, `belong`, `params`)
	              VALUES (
	                 '. $field_id .',
	                 '. $nodeId .', 99, 0,
	                 "'. $f['name'] .'",
	                 "'. $f['name'] .'",
	                 "'. $f['belong'] .'",
	                 "'. mysql_real_escape_string(serialize($params)) .'"
	              )';
         $DB->DB_Query();
      }


      if($ErrorHandler->getErrorStatus() == FALSE)
      {
         $DB->DB_EndTransaction();
         $ErrorHandler->setSuccess(array('menu'=>array('newfield'=>'/admin/addfield'. ($nodeId ? '/'. $nodeId .'.html' : '.html'))));
      }
   }
   else
   {
      $SMARTY->assign('c', $category);
      $layout = 'addfield.html';
   }
}
else
{
   if (session::user())
   {
      $ErrorHandler->setError(
              array(
                  'code' => 'access',
                  'varkey' => 'access_denied'
              )
      );
   }
   $layout = 'login.html';
}

/*
   'type' => string 'string|integer|float|logic|select|multiselect|article|category|date|file|uploads' (length=4)
   'html' => boolean false
   'height' => integer
   'emode' => string (editor mode)
   'value' => boolean false
   'values' => string (langphrase)
   'min_w' => integer
   'min_h' => integer
   'max_w' => integer
   'max_h' => integer
   'fixed' => bool
   'belong' => string
   'fieldset' => string
   'db' => string
 */